package com.ruyipu.forum.model;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;

import com.ruyipu.forum.base.FileReader;
import com.ruyipu.forum.base.FileWriter;
import com.ruyipu.forum.base.MyLog;
import com.ruyipu.forum.base.TextService;

public final class Model {

	public static final String TAG = Model.class.getSimpleName();

	public static final int SUCCESS = 0;
	public static final int ERROR_COMMEN = 1;
	public static final int ERROR_NO_DATA = 2;

	public static final int EXCEPTION = -1;
	public static final int EXCEPTION_UNSUPPORTED_ENCODING = -2;
	public static final int EXCEPTION_CLIENT_PROTOCAL = -3;
	public static final int EXCEPTION_IO = -4;
	public static final int EXCEPTION_JSON = -5;

	private Model() {
	}

	public static JSONObject get(Context context, String url)
			throws UnsupportedEncodingException, ClientProtocolException,
			IOException, JSONException {
		return post(context, url, null);
	}

	public static JSONObject post(Context context, String url,
			List<NameValuePair> params) throws UnsupportedEncodingException,
			ClientProtocolException, IOException, JSONException {
		JSONObject jsonObject = null;
		if (null == context || null == url || "".equals(url)) {
			return null;
		}
		jsonObject = TextService.execute(context, url, params);
		return jsonObject;
	}

	public static JSONObject loadLocalData(String url) throws JSONException {
		String fileName = FileWriter.fixJSONFileName(url);
		String content = FileReader.readFile(fileName);
		if (null != content && !"".equals(content)) {
			JSONObject jsonObject = new JSONObject(content);
			if (null != jsonObject) {
				return jsonObject;
			}
		}
		return null;
	}
}
